package com.song.kkxxpoi;

import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class PortScanner {
    // private static final String HOSTNAME = "test.rs-xrys.com"; // 替换为你的域名
    private static final String HOSTNAME = "ols.v.zzu.edu.cn"; // 替换为你的域名
    private static final int START_PORT = 1;
    // private static final int END_PORT = 1992;
    private static final int END_PORT = 65536;
    private static final int TIMEOUT = 100; // 设置连接超时时间

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(1000); // 创建线程池
        int[] openPortsCount = {0}; // 使用数组以便在内部类中修改

        for (int port = START_PORT; port <= END_PORT; port++) {
            final int currentPort = port; // final 变量用于 lambda 表达式
            executor.submit(() -> {
                try (Socket socket = new Socket(HOSTNAME, currentPort)) {
                    socket.setSoTimeout(TIMEOUT); // 设置超时时间
                    System.out.println("Port " + currentPort + " 是开放的");
                    synchronized (openPortsCount) { // 线程安全地增加计数
                        openPortsCount[0]++;
                    }
                } catch (Exception e) {
                    // 端口未打开，捕获异常
                }
            });
        }

        executor.shutdown(); // 关闭线程池
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // 等待所有任务完成
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 恢复中断状态
        }

        System.out.println("开放端口总数: " + openPortsCount[0]);
    }
}
